package controller

import (
	"context"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"net/http"
	"user_bff/pkg"
	"user_bff/proto"
)

// 用户登录注册
func UserLogin(c *gin.Context) {
	mobile := c.PostForm("mobile")
	password := c.PostForm("password")
	code := c.PostForm("code")
	if mobile == "" || password == "" || code == "" {
		c.JSON(http.StatusNotFound, gin.H{
			"code": -1,
			"msg":  "参数不能为空",
			"data": nil,
		})
		return
	}
	//远程连接srv
	comment := pkg.Comment()
	byMobile, err := comment.GetUserByMobile(context.Background(), &proto.GetUserByMobileRequest{Mobile: mobile})
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "注册成功,请重新登录",
			"data": nil,
		})
		//用户注册
		_, err := comment.UserRegister(context.Background(), &proto.UserRegisterRequest{
			Mobile:   mobile,
			Password: pkg.Md5(password),
		})
		if err != nil {
			c.JSON(http.StatusNotFound, gin.H{
				"code": -1,
				"msg":  "用户注册失败",
				"data": nil,
			})
			return
		}
	}
	//判断密码是否正确
	if pkg.Md5(password) != byMobile.Password {
		c.JSON(http.StatusNotFound, gin.H{
			"code": -1,
			"msg":  "密码错误",
			"data": nil,
		})
		return
	}
	//获取 短信验证吗
	sms, err := pkg.GetSendSms(mobile)
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{
			"code": -1,
			"msg":  "获取短信验证码失败",
			"data": nil,
		})
		return
	}
	//判断验证码是否正确
	if code != sms {
		c.JSON(http.StatusNotFound, gin.H{
			"code": -1,
			"msg":  "短信验证码错误",
			"data": nil,
		})
		return
	}
	//生成token
	marshal, _ := json.Marshal(byMobile)
	token, err := pkg.SetJwtToken(string(marshal))
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{
			"code": -1,
			"msg":  "token生成失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "登录成功",
		"data": token,
	})
	return
}
